<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\Rbac\RouteCode;
use App\Constants\Rbac\TokenCode;
use App\Exception\HeaderErrorException;
use App\Service\Admin\AdminService;
use App\Service\User\UserService;
use App\Utils\ContextUtil;
use App\Utils\JWT\Exceptions\TokenInvalidException;
use App\Utils\JWT\Token;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 尝试解析token
 */
class TokenMiddleware implements MiddlewareInterface
{
    public function __construct(protected ContainerInterface $container,HttpResponse $response, RequestInterface $request)
    {
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->parseValidToken();
        return $handler->handle($request);
    }

    protected function parseValidToken()
    {
        $token = $this->request->header(RouteCode::HEADER_TOKEN);
        if (empty($token)){
            return;
        }
        try {
            $tokenIns = Token::parseRawToken($token);
            $payload = $tokenIns->payload;
            if ($payload->exp < time()){
                return;
            }
            // 根据不同业务端判断jti
            $aud = $payload->aud;
            if ($aud == TokenCode::LOGIN_USER){
                // 限制单点登录
                $user = \Hyperf\Support\make(UserService::class)->userBaseInfo($payload->uid);
                ContextUtil::setUser($user);
            }elseif ($aud == TokenCode::LOGIN_ADMIN){
                $admin = \Hyperf\Support\make(AdminService::class)->adminBaseInfo($payload->uid);
                ContextUtil::setAdmin($admin);
            }
        }catch (TokenInvalidException $e){

        }
    }
}
